//app.js
const Util = require('./utils/util.js');

App({
    onLaunch: function () {

    },

    globalData: {
        userInfo: null,
        problemList: [],
        problemIndex: 0,
        quizFinished: false,
        userId: '',
        userName: '',
        baseURL: 'http://172.17.128.141:3000/',
        wrongBook: null,
        exerciseMode: false,
        gradeName: '',
        subject: '',
        groupName: '',
        tenantId: ''
    },

    login: function (userId, userName) {
        this.globalData.userId = userId;
        this.globalData.userName = userName;
        wx.setStorageSync('user', JSON.stringify({
            userId: this.globalData.userId,
            userName: this.globalData.userName
        }));
    },

    logout: function () {
        wx.setStorageSync('user', undefined);
    },

    installQuestionSet: function (questions) {
        this.globalData.problemList = questions;
        this.globalData.problemIndex = 0;
        this.globalData.quizFinished = false;
    },
    
    forward: function (answer) {
        let index = this.globalData.problemIndex;
        if (index < 0 || index >= this.globalData.problemList.length) {
            return;
        }
        if (answer >= 0) {
            this.globalData.problemList[index].answer = answer;
            if (this.globalData.problemList[index].options[answer].isRight) {
                this.globalData.score += 1;
            }
        }
        if (index < this.globalData.problemList.length - 1) {
            this.globalData.problemIndex += 1;
        }
    },

    backward: function () {
        if (this.globalData.problemIndex > 0) {
            this.globalData.problemIndex -= 1;
        }
    },

    deleteQuestion: async function (questionId) {
        let b = this.globalData.baseURL;
        await Util.asyncHttpPost(b + 'deleteWrong', {
            userId: this.globalData.userId,
            quesId: questionId
        });
    },

    getWrongBook: async function () {
        this.globalData.wrongBook = [];
        let b = this.globalData.baseURL;
        let result = await Util.asyncHttpPost(b + 'wrongQues', {
            userId: this.globalData.userId
        });
        for (let item of result.data) {
            let url = b + 'findQuestion?data=' + item.quesId;
            let resp = await Util.asyncHttpGet(url);
            this.globalData.wrongBook.push(resp.data.data);
        }
        return this.globalData.wrongBook;
    },

    addToWrongBook: async function () {
        let questionId = this.globalData.problemList[this.globalData.problemIndex].id;
        let b = this.globalData.baseURL;
        let result = await Util.asyncHttpPost(b + 'addWrong', {
            userId: this.globalData.userId,
            quesId: questionId
        });
        if (this.globalData.wrongBook) {
            this.globalData.wrongBook.push(this.globalData.problemList[this.globalData.problemIndex])
        }
        console.log(result);
    }
})